package com.b2c.erp.controller.shop.douyin;

import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.douyin.DouyinOrderStatisticsEntity;
import com.b2c.entity.enums.third.EnumDouYinOrderStatus;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.ErpContactEntity;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.wms.ClientManageService;
import com.b2c.interfaces.dou.DouyinOrderService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 直播间销售统计
 */
@Controller
@RequestMapping("/zbj")
public class DouyinOrderStatisticsController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private DouyinOrderService douyinOrderService;
    @Autowired
    private ClientManageService clientManageService;

    /**
     * 订单列表
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/sales_statistics_douyin")
    public String orderList(Model model, HttpServletRequest request){

        //查询店铺信息

        var shopList = shopService.getShopList(6);
        model.addAttribute("shopList",shopList);
        Integer shopId = shopList.get(0).getId();
        model.addAttribute("shopId",shopId);

        //直播账号
        int type=-10;
        PagingResponse<ErpContactEntity> zbjList = clientManageService.getClientList(1, 10, null, null,type,99);
        model.addAttribute("zbjList", zbjList.getList());

        String orderDate="";
        if (!StringUtils.isEmpty(request.getParameter("orderDate"))) {
            orderDate = request.getParameter("orderDate");
        }else{
            Date yesToday = new Date(System.currentTimeMillis() - 1000 * 60 * 60 *  24);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            orderDate = simpleDateFormat.format(yesToday);
        }
        model.addAttribute("orderDate", orderDate);

        if (!StringUtils.isEmpty(request.getParameter("shopId"))) {
            shopId = Integer.parseInt(request.getParameter("shopId"));
            model.addAttribute("shopId", shopId);
        }
        Long authorId = null;
        if (!StringUtils.isEmpty(request.getParameter("authorId"))) {
            authorId = Long.parseLong(request.getParameter("authorId"));
            model.addAttribute("authorId", authorId);
        }


        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }

        PagingResponse<DouyinOrderStatisticsEntity> result = douyinOrderService.getOrderStatisticsList(pageIndex,pageSize,orderDate,shopId,authorId);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());




        model.addAttribute("view", "livedata");
        model.addAttribute("pView", "sale");

        return "order/douyin/order_statistics_douyin";
    }

    @ResponseBody
    @RequestMapping(value = "/list_dy_export")
    public void erpStockOutItemRefundInvoiceExport(HttpServletRequest req, HttpServletResponse response) throws Exception {

        String orderDate="";
        if (!StringUtils.isEmpty(req.getParameter("orderDate"))) {
            orderDate = req.getParameter("orderDate");
        }

        Integer shopId = null;
        if (!StringUtils.isEmpty(req.getParameter("shopId"))) {
            shopId = Integer.parseInt(req.getParameter("shopId"));
        }
        Long authorId = null;
        if (!StringUtils.isEmpty(req.getParameter("authorId"))) {
            authorId = Long.parseLong(req.getParameter("authorId"));
        }

        List<DouyinOrderStatisticsEntity> lists = douyinOrderService.getOrderStatisticsListExport(orderDate,shopId,authorId);



        /***************根据店铺查询订单导出的信息*****************/
        String fileName = "zbj_sales_list_douyin_export_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        //第一行为空
        row = sheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("序号");
        cell = row.createCell(1);
        cell.setCellValue("下单日期");
        cell = row.createCell(2);
        cell.setCellValue("商品编码");
        cell = row.createCell(3);
        cell.setCellValue("规格编码");
        cell = row.createCell(4);
        cell.setCellValue("数量");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("销售金额");
        cell = row.createCell(7);
        cell.setCellValue("运费成本");
        cell = row.createCell(8);
        cell.setCellValue("毛利");
        cell = row.createCell(9);
        cell.setCellValue("主播");
        cell = row.createCell(10);
        cell.setCellValue("店铺");
        cell = row.createCell(11);
        cell.setCellValue("状态");

        int currRowNum = 0;
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 循环写入数据
        for (int i = 0; i < lists.size(); i++) {
            currRowNum++;
            //写入订单
            DouyinOrderStatisticsEntity itemVo = lists.get(i);
            //创建行
            row = sheet.createRow(currRowNum);
            cell = row.createCell(0);
            cell.setCellValue(i);

            cell = row.createCell(1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            cell.setCellValue(simpleDateFormat.format(itemVo.getCreateTime() * 1000));
            //商品编码
            cell = row.createCell(2);
            cell.setCellValue(itemVo.getProductNum());

            cell = row.createCell(3);
            cell.setCellValue(itemVo.getSpecNum());

            cell = row.createCell(4);
            cell.setCellValue(itemVo.getNum());

            //成本
            cell = row.createCell(5);
            BigDecimal zcb = itemVo.getCostPrice().multiply(new BigDecimal(itemVo.getNum()));
            cell.setCellValue(zcb.doubleValue());
            //销售金额
            cell = row.createCell(6);
            cell.setCellValue(itemVo.getTotalAmount().doubleValue());
            cell = row.createCell(7);
            cell.setCellValue(5);
            //毛利
            cell = row.createCell(8);
            cell.setCellValue(itemVo.getTotalAmount().subtract(zcb).doubleValue()-5.0);

            cell = row.createCell(9);
            cell.setCellValue(itemVo.getAuthorName());
            cell = row.createCell(10);
            cell.setCellValue(itemVo.getShopName());
            cell = row.createCell(11);
            cell.setCellValue(EnumDouYinOrderStatus.getThirdStatusName(itemVo.getOrderStatus()));

        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((fileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }
    }
}
